<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example 中文版: 速率限制</title>
    <link rel=stylesheet href="site.css">
  </head>
  <script>
      onkeydown = (e) => {
          
          if (e.key == "ArrowLeft") {
              window.location.href = 'waitgroups';
          }
          
          
          if (e.key == "ArrowRight") {
              window.location.href = 'atomic-counters';
          }
          
      }
  </script>
  <body>

    <div class="example" id="rate-limiting">
      <h2><a href="./">Go by Example 中文版</a>: 速率限制</h2>
      
      <table>
        
        <tr>
          <td class="docs">
            <p><em><a href="http://en.wikipedia.org/wiki/Rate_limiting">速率限制</a></em>
是控制服务资源利用和质量的重要机制。
基于协程、通道和<a href="tickers">打点器</a>，Go 优雅的支持速率限制。</p>

          </td>
          <td class="code empty leading">
            
          
          </td>
        </tr>
        
        <tr>
          <td class="docs">
            
          </td>
          <td class="code leading">
            <a href="http://play.golang.org/p/J02ZVgmF75x"><img title="Run code" src="play.png" class="run" /></a><img title="Copy code" src="clipboard.png" class="copy" />
          <div class="highlight"><pre><span class="kn">package</span> <span class="nx">main</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            
          </td>
          <td class="code leading">
            
          <div class="highlight"><pre><span class="kn">import</span> <span class="p">(</span>
    <span class="s">&quot;fmt&quot;</span>
    <span class="s">&quot;time&quot;</span>
<span class="p">)</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            
          </td>
          <td class="code leading">
            
          <div class="highlight"><pre><span class="kd">func</span> <span class="nx">main</span><span class="p">()</span> <span class="p">{</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>首先，我们将看一个基本的速率限制。
假设我们想限制对收到请求的处理，我们可以通过一个渠道处理这些请求。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="nx">requests</span> <span class="o">:=</span> <span class="nb">make</span><span class="p">(</span><span class="kd">chan</span> <span class="kt">int</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
    <span class="k">for</span> <span class="nx">i</span> <span class="o">:=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">{</span>
        <span class="nx">requests</span> <span class="o">&lt;-</span> <span class="nx">i</span>
    <span class="p">}</span>
    <span class="nb">close</span><span class="p">(</span><span class="nx">requests</span><span class="p">)</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p><code>limiter</code> 通道每 200ms 接收一个值。
这是我们任务速率限制的调度器。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="nx">limiter</span> <span class="o">:=</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Tick</span><span class="p">(</span><span class="mi">200</span> <span class="o">*</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Millisecond</span><span class="p">)</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>通过在每次请求前阻塞 <code>limiter</code> 通道的一个接收，
可以将频率限制为，每 200ms 执行一次请求。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="k">for</span> <span class="nx">req</span> <span class="o">:=</span> <span class="k">range</span> <span class="nx">requests</span> <span class="p">{</span>
        <span class="o">&lt;-</span><span class="nx">limiter</span>
        <span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;request&quot;</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Now</span><span class="p">())</span>
    <span class="p">}</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>有时候我们可能希望在速率限制方案中允许短暂的并发请求，并同时保留总体速率限制。
我们可以通过缓冲通道来完成此任务。
<code>burstyLimiter</code> 通道允许最多 3 个爆发（bursts）事件。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="nx">burstyLimiter</span> <span class="o">:=</span> <span class="nb">make</span><span class="p">(</span><span class="kd">chan</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Time</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>填充通道，表示允许的爆发（bursts）。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="k">for</span> <span class="nx">i</span> <span class="o">:=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="p">&lt;</span> <span class="mi">3</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">{</span>
        <span class="nx">burstyLimiter</span> <span class="o">&lt;-</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Now</span><span class="p">()</span>
    <span class="p">}</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>每 200ms 我们将尝试添加一个新的值到 <code>burstyLimiter</code>中，
直到达到 3 个的限制。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre>    <span class="k">go</span> <span class="kd">func</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">for</span> <span class="nx">t</span> <span class="o">:=</span> <span class="k">range</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Tick</span><span class="p">(</span><span class="mi">200</span> <span class="o">*</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Millisecond</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">burstyLimiter</span> <span class="o">&lt;-</span> <span class="nx">t</span>
        <span class="p">}</span>
    <span class="p">}()</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>现在，模拟另外 5 个传入请求。
受益于 <code>burstyLimiter</code> 的爆发（bursts）能力，前 3 个请求可以快速完成。</p>

          </td>
          <td class="code">
            
          <div class="highlight"><pre>    <span class="nx">burstyRequests</span> <span class="o">:=</span> <span class="nb">make</span><span class="p">(</span><span class="kd">chan</span> <span class="kt">int</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
    <span class="k">for</span> <span class="nx">i</span> <span class="o">:=</span> <span class="mi">1</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;=</span> <span class="mi">5</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span> <span class="p">{</span>
        <span class="nx">burstyRequests</span> <span class="o">&lt;-</span> <span class="nx">i</span>
    <span class="p">}</span>
    <span class="nb">close</span><span class="p">(</span><span class="nx">burstyRequests</span><span class="p">)</span>
    <span class="k">for</span> <span class="nx">req</span> <span class="o">:=</span> <span class="k">range</span> <span class="nx">burstyRequests</span> <span class="p">{</span>
        <span class="o">&lt;-</span><span class="nx">burstyLimiter</span>
        <span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;request&quot;</span><span class="p">,</span> <span class="nx">req</span><span class="p">,</span> <span class="nx">time</span><span class="p">.</span><span class="nx">Now</span><span class="p">())</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>

          </td>
        </tr>
        
      </table>
      
      <table>
        
        <tr>
          <td class="docs">
            <p>运行程序，我们看到第一批请求意料之中的大约每 200ms 处理一次。</p>

          </td>
          <td class="code leading">
            
          <div class="highlight"><pre><span class="gp">$</span> go run rate-limiting.go
<span class="go">request 1 2012-10-19 00:38:18.687438 +0000 UTC</span>
<span class="go">request 2 2012-10-19 00:38:18.887471 +0000 UTC</span>
<span class="go">request 3 2012-10-19 00:38:19.087238 +0000 UTC</span>
<span class="go">request 4 2012-10-19 00:38:19.287338 +0000 UTC</span>
<span class="go">request 5 2012-10-19 00:38:19.487331 +0000 UTC</span>
</pre></div>

          </td>
        </tr>
        
        <tr>
          <td class="docs">
            <p>第二批请求，由于爆发（burstable）速率控制，我们直接连续处理了 3 个请求，
然后以大约每 200ms 一次的速度，处理了剩余的 2 个请求。</p>

          </td>
          <td class="code">
            
          <div class="highlight"><pre><span class="go">request 1 2012-10-19 00:38:20.487578 +0000 UTC</span>
<span class="go">request 2 2012-10-19 00:38:20.487645 +0000 UTC</span>
<span class="go">request 3 2012-10-19 00:38:20.487676 +0000 UTC</span>
<span class="go">request 4 2012-10-19 00:38:20.687483 +0000 UTC</span>
<span class="go">request 5 2012-10-19 00:38:20.887542 +0000 UTC</span>
</pre></div>

          </td>
        </tr>
        
      </table>
      
      
      <p class="next">
        下一个例子: <a href="atomic-counters">原子计数器</a>
      </p>
      
      <p class="footer">
        <a href="https://twitter.com/mmcgrana">@mmcgrana</a> 编写 | <a href="https://github.com/gobyexample-cn">gobyexample-cn</a> 翻译 | <a href="https://github.com/gobyexample-cn/gobyexample/issues">反馈</a> | <a href="https://github.com/gobyexample-cn/gobyexample">源码</a> | <a href="https://github.com/mmcgrana/gobyexample#license">license</a>      </p>
      </p>
    </div>
    <script>
      var codeLines = [];
      codeLines.push('');codeLines.push('package main\u000A');codeLines.push('import (\u000A    \"fmt\"\u000A    \"time\"\u000A)\u000A');codeLines.push('func main() {\u000A');codeLines.push('    requests := make(chan int, 5)\u000A    for i := 1; i \x3C= 5; i++ {\u000A        requests \x3C- i\u000A    }\u000A    close(requests)\u000A');codeLines.push('    limiter := time.Tick(200 * time.Millisecond)\u000A');codeLines.push('    for req := range requests {\u000A        \x3C-limiter\u000A        fmt.Println(\"request\", req, time.Now())\u000A    }\u000A');codeLines.push('    burstyLimiter := make(chan time.Time, 3)\u000A');codeLines.push('    for i := 0; i \x3C 3; i++ {\u000A        burstyLimiter \x3C- time.Now()\u000A    }\u000A');codeLines.push('    go func() {\u000A        for t := range time.Tick(200 * time.Millisecond) {\u000A            burstyLimiter \x3C- t\u000A        }\u000A    }()\u000A');codeLines.push('    burstyRequests := make(chan int, 5)\u000A    for i := 1; i \x3C= 5; i++ {\u000A        burstyRequests \x3C- i\u000A    }\u000A    close(burstyRequests)\u000A    for req := range burstyRequests {\u000A        \x3C-burstyLimiter\u000A        fmt.Println(\"request\", req, time.Now())\u000A    }\u000A}\u000A');codeLines.push('');codeLines.push('');
    </script>
    <script src="site.js" async></script>
  </body>
</html>
